package cn.ctyun.videoplayer.playerevent;

import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import cn.ctyun.videoplayer.bean.TerminalInfo;
import cn.ctyun.videoplayer.bean.VideoInfo;
import cn.ctyun.videoplayer.bean.VideoModel;
import cn.ctyun.videoplayer.player.BaseIjkVideoView;
import cn.ctyun.videoplayer.util.PlayerConstants;
import cn.ctyun.videoplayer.util.SharePreferencesUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PlayerEventManager {

    private static final String TAG = PlayerEventManager.class.getSimpleName();
    private static final String PARAM_KEY_PLAYER_EVENT_LIST = "PLAYER_EVENT_LIST";
    private static final String UPLOAD_URL = "http://10.142.232.138:8776/mstor-server/video/data/collect";

    private static PlayerEventManager INSTANCE = null;
    private static SharePreferencesUtils mSharePreferencesUtils;
    private Context mContext;
//    private BaseIjkVideoView mVideoView;

    private PlayerEventManager(Context context) {
        this.mContext = context;
        mSharePreferencesUtils = new SharePreferencesUtils(context, "USER_PLAYER_DATA");
    }

    public static PlayerEventManager getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new PlayerEventManager(context);
        }
        return INSTANCE;
    }

    public void savePlayerEvent(String action, BaseIjkVideoView videoView) {

        if (!videoView.isEnableRecordPlayerEvent()) {
            return;
        }

        PlayerEventModel playerEventModel = new PlayerEventModel();
        playerEventModel.setAction(action);
        playerEventModel.setTerminal(getTerminalInfo(mContext));
        playerEventModel.setVideo(getVideoInfo(mContext, videoView));

        Log.d(TAG, playerEventModel.toString());

        List<PlayerEventModel> playerEventModels = null;
        try {
            playerEventModels = (List<PlayerEventModel>)mSharePreferencesUtils.getSerializableObject(PARAM_KEY_PLAYER_EVENT_LIST);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        if (playerEventModels == null) {
            playerEventModels = new ArrayList<>();
        }

        try {
            playerEventModels.add(playerEventModel);
            mSharePreferencesUtils.setSerializableObject(PARAM_KEY_PLAYER_EVENT_LIST, playerEventModels);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "保存播放器数据出错:" + e.getMessage());
        }

    }

    public void uploadPlayerEventData() {

        Log.d(TAG, "开始上传播放器打点数据");
        try {
            final List<PlayerEventModel> playerEventModels = (List<PlayerEventModel>)mSharePreferencesUtils.getSerializableObject(PARAM_KEY_PLAYER_EVENT_LIST);
            if (playerEventModels != null) {
//                final HashMap<String, String> paramsMap = new HashMap<>();
//                paramsMap.put("playerEvent", JSON.toJSONString(playerEventModels));
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        requestPostPlayerEventData(JSON.toJSONString(playerEventModels));
//                    }
//                }).start();

                requestPostPlayerEventData(JSON.toJSONString(playerEventModels));

            }
        } catch (Exception e) {
            Log.d(TAG, "上传播放器打点数据失败 : " + e.getMessage());
        }
    }

//    public static final MediaType MediaTypeJSON = MediaType.parse("application/json; charset=utf-8");

    private void requestPostPlayerEventData(String playerEventsJson) {

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("videoDataArrayJson", playerEventsJson)
                .build();
        Request request = new Request.Builder()
                .url(UPLOAD_URL)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "上传打点数据失败 : " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
//                Headers headers = response.headers();
//                for (int i = 0; i < headers.size(); i++) {
//                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
//                }
                Log.d(TAG, "上传打点数据成功 : " + response.body().string());
            }
        });

    }

    private static TerminalInfo getTerminalInfo(Context context) {
        TerminalInfo terminalInfo = new TerminalInfo();
        terminalInfo.setPlatform(Build.MANUFACTURER + "/" + Build.MODEL + "/" + Build.VERSION.SDK_INT);
        terminalInfo.setApp(PlayerEventUtils.getAppName(context));
        terminalInfo.setNetwork(PlayerEventUtils.getNetworkTypeString(context));
        String uniqueId = mSharePreferencesUtils.getStringValue("uniqueId");
        if (TextUtils.isEmpty(uniqueId)) {
            UUID uuid = UUID.randomUUID();
            uniqueId = uuid.toString();
            mSharePreferencesUtils.setStringValue("uniqueId", uniqueId);
        }
        terminalInfo.setUserHash(uniqueId);
        terminalInfo.setTime(PlayerEventUtils.getCurrentTime());
        return terminalInfo;
    }

    private static VideoInfo getVideoInfo(Context context, BaseIjkVideoView baseIjkVideoView) {
        VideoInfo videoInfo = new VideoInfo();
        if (baseIjkVideoView != null) {


            String currentVideoType = PlayerConstants.VideoType.VIDEO;
            String currentUrl = baseIjkVideoView.getCurrentUrl();
            List<VideoModel> videos = baseIjkVideoView.getVideos();
            if (videos != null && videos.size() > 0) {
                for (VideoModel videoModel : videos) {
                    if (PlayerConstants.VideoType.START_AD.equals(videoModel.getVideoType())) {
                        videoInfo.setStartAdUrl(videoModel.getUrl());
                        if (currentUrl.equals(videoModel.getUrl())) {
                            currentVideoType = PlayerConstants.VideoType.START_AD;
                        }
                    } else if (PlayerConstants.VideoType.END_AD.equals(videoModel.getVideoType())) {
                        videoInfo.setEndAdUrl(videoModel.getUrl());
                        if (currentUrl.equals(videoModel.getUrl())) {
                            currentVideoType = PlayerConstants.VideoType.END_AD;
                        }
                    } else {
                        videoInfo.setVideoUrl(videoModel.getUrl());
                    }

                }
            }

            videoInfo.setPauseAdUrl(baseIjkVideoView.getPauseAdUrl());
            videoInfo.setCurrentPosition(baseIjkVideoView.getCurrentPosition()+"");

            // Playing/Pause/Stop/Error/StartAd/EndAd
            if (PlayerConstants.VideoType.START_AD.equals(currentVideoType)) {
                videoInfo.setCurrentStatus("StartAd");
            } else if (PlayerConstants.VideoType.END_AD.equals(currentVideoType)) {
                videoInfo.setCurrentStatus("EndAd");
            } else {
                if (baseIjkVideoView.getCurrentPlayState() == BaseIjkVideoView.STATE_PLAYING) {
                    videoInfo.setCurrentStatus("Playing");
                } else if (baseIjkVideoView.getCurrentPlayState() == BaseIjkVideoView.STATE_PAUSED) {
                    videoInfo.setCurrentStatus("Pause");
                } else if (baseIjkVideoView.getCurrentPlayState() == BaseIjkVideoView.STATE_PLAYBACK_COMPLETED) {
                    videoInfo.setCurrentStatus("Stop");
                } else if (baseIjkVideoView.getCurrentPlayState() == BaseIjkVideoView.STATE_ERROR) {
                    videoInfo.setCurrentStatus("Error");
                }
            }

            // 音量百分比
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            int streamMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            int streamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String percent = numberFormat.format((float)streamVolume/(float)streamMaxVolume*100);
            videoInfo.setVolume(percent + "%");

            videoInfo.setSpeed(baseIjkVideoView.getSpeed() + "X");
            // 缓冲时间百分比
            videoInfo.setBufferedTimeRange(baseIjkVideoView.getBufferedPercentage() + "%");
            // 可播放时长
            long playableVideoDuration = baseIjkVideoView.getPlayableVideoDuration();
            long duration = baseIjkVideoView.getDuration();
            if (playableVideoDuration > 0 && playableVideoDuration < duration) {
                duration = playableVideoDuration;
            }
            videoInfo.setPlayableVideoDuration(duration + "");

        }
        return videoInfo;
    }

}
